/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.facilscrum.form.userstories;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.facilscrum.beans.Equiposusuarios;
import org.javscaz.javscaztools.utilidades.Utilidades;
import org.facilscrum.beans.Proyectos;
import org.facilscrum.beans.Userstories;
import org.facilscrum.beans.Usuarios;
import org.facilscrum.controller.EquiposusuariosController;
import org.facilscrum.controller.ProyectosController;
import org.facilscrum.controller.UserstoriesController;
import org.facilscrum.controller.UsuariosController;
import org.facilscrum.form.usuarios.UsuariosForm;
import org.facilscrum.generales.Mensajeria;
import org.facilscrum.sesion.MySesion;

/**
 *
 * @author avbravo
 */
public class UserstoriesImprimirForm extends javax.swing.JInternalFrame {

    EquiposusuariosController equiposusuariosController = new EquiposusuariosController();
    ProyectosController proyectosController = new ProyectosController();
    UserstoriesController userstoriesController = new UserstoriesController();
    Userstories userstories = new Userstories();
    UsuariosController usuariosController = new UsuariosController();
    Usuarios usuarios = new Usuarios();
    DefaultTableModel modelo;

    /**
     * Creates new form BacklogForm
     */
    public UserstoriesImprimirForm() {
        initComponents();
        modelo = (DefaultTableModel) jTable1.getModel();
        jTable1.setEnabled(true);


        if (!MySesion.getSeleccionoProyectoTrabajo()) {
            Mensajeria.MensajeWarning("Debe indicar el proyecto de trabajo");
        } else {

            jTextFieldProyecto.setText(MySesion.getProyectos().getProyecto());
        }
        cargarUserStories("no");

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButtonCerrar = new javax.swing.JButton();
        jTextFieldProyecto = new javax.swing.JTextField();
        jButtonImprimir = new javax.swing.JButton();
        jCheckBoxNoAsignado = new javax.swing.JCheckBox();
        jCheckBoxAsignado = new javax.swing.JCheckBox();
        jCheckBoxTodos = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Informes de  User stories");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Proyecto");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "nombre", "importancia", "puntos", "usuario"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(60);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(100);
        jTable1.getColumnModel().getColumn(3).setMaxWidth(60);

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/return.gif"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jTextFieldProyecto.setEnabled(false);

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/print.png"))); // NOI18N
        jButtonImprimir.setToolTipText("Eliminar");
        jButtonImprimir.setEnabled(false);
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        buttonGroup1.add(jCheckBoxNoAsignado);
        jCheckBoxNoAsignado.setSelected(true);
        jCheckBoxNoAsignado.setText("Sin asignacion al sprint");
        jCheckBoxNoAsignado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxNoAsignadoActionPerformed(evt);
            }
        });

        buttonGroup1.add(jCheckBoxAsignado);
        jCheckBoxAsignado.setText("Asignado");
        jCheckBoxAsignado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxAsignadoActionPerformed(evt);
            }
        });

        buttonGroup1.add(jCheckBoxTodos);
        jCheckBoxTodos.setText("Todos");
        jCheckBoxTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxTodosActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel2.setText("Si desea imprimir uno individual haga clic en el userstories...");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 6, Short.MAX_VALUE))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(233, 233, 233)
                                .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(51, 51, 51)
                                .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jCheckBoxNoAsignado)
                                .addGap(18, 18, 18)
                                .addComponent(jCheckBoxAsignado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jCheckBoxTodos)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBoxNoAsignado)
                    .addComponent(jCheckBoxAsignado)
                    .addComponent(jCheckBoxTodos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonImprimir)
                    .addComponent(jButtonCerrar))
                .addGap(9, 9, 9)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            Integer fila = jTable1.getSelectedRow();
            if (fila == -1) {
                Mensajeria.Mensaje("No se selecciono ninguna fila");

                return;
            }
            userstories.setIduserstories(Integer.parseInt(jTable1.getValueAt(fila, 0).toString()));
            Userstories us = userstoriesController.findByPrimaryKey(userstories);
            if (userstories != null) {
                userstories = us;
            } else {
                Mensajeria.MensajeWarning("No existe un userstories con ese codigo");

                return;
            }



            Usuarios u = new Usuarios();
            u.setUsername(userstories.getUsername());
            u = usuariosController.findByPrimaryKey(u);
            if (Mensajeria.PreguntaSiNo("Desea imprimirlo", "imprimir").equals("si")) {
                HashMap map = new HashMap();
                List<Userstories> list = new ArrayList();
                list.add(userstories);
                try {
                    imprimir(list, map);
                } catch (JRException ex) {
                    Logger.getLogger(UsuariosForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }


        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "MouseClicked()");
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
        HashMap map = new HashMap();

        try {
            imprimir(userstoriesController.getUserstorieslist(), map);
        } catch (JRException ex) {
            Logger.getLogger(UsuariosForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonImprimirActionPerformed

    private void jCheckBoxNoAsignadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxNoAsignadoActionPerformed
        cargarUserStories("no");
    }//GEN-LAST:event_jCheckBoxNoAsignadoActionPerformed

    private void jCheckBoxAsignadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxAsignadoActionPerformed
        cargarUserStories("si");
    }//GEN-LAST:event_jCheckBoxAsignadoActionPerformed

    private void jCheckBoxTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTodosActionPerformed
        cargarUserStories("todos");
    }//GEN-LAST:event_jCheckBoxTodosActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JCheckBox jCheckBoxAsignado;
    private javax.swing.JCheckBox jCheckBoxNoAsignado;
    private javax.swing.JCheckBox jCheckBoxTodos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldProyecto;
    // End of variables declaration//GEN-END:variables

    private void cargarUserStories(String asignado) {
        try {
            Proyectos proyectos = MySesion.getProyectos();
            modelo = Utilidades.limpiarModelo(modelo);
            String sql = "asignado='" + asignado + "' and idproyecto='" + proyectos.getIdproyecto() + "' order by importancia desc";
            if (asignado.equals("todos")) {
                sql = "idproyecto='" + proyectos.getIdproyecto() + "' order by importancia desc";
            }
            if (userstoriesController.query(sql)) {
                for (Userstories u : userstoriesController.getUserstorieslist()) {
                    Object[] filas = new Object[5]; // Hay tres columnas en la tabla       
                    filas[0] = u.getIduserstories();
                    filas[1] = u.getNombre();
                    filas[2] = u.getImportancia();
                    filas[3] = u.getPuntos();
                    filas[4] = u.getUsuarios().getNombre();
                    modelo.addRow(filas);
                }
                jButtonImprimir.setEnabled(true);
            }


        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarUserStories()");

        }
    }

    private void imprimir(List<Userstories> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
//Indicamos la ruta del reporte
            InputStream reporte = (InputStream) getClass().getResourceAsStream("/org/facilscrum/reportes/userstories.jasper");
            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }
}
